#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <istream>
#include <fstream>
#include <sstream>
using namespace std;
class TextQuery{
public:
    void read(const string & filename){
        ifstream ifs(filename);
        string line;
        //记录行号
        int lineNum = 0;
        while(getline(ifs,line)){
            ++lineNum;
            //将读取的每行数据存入动态数组中
            _lines.push_back(line);
            istringstream iss(line);
            string word;
            while(iss >> word){
               _wordnums[word].insert(lineNum);
               ++_dict[word];
        }
   }
}
void query(const string & word){
      cout << "==========================="<<endl;
      cout<<word<<"occurs"<<_dict[word] <<"times"<<endl;
      for(auto & linenumber : _wordnums[word]){
          cout<<"(line"<<linenumber <<")"<<_lines[linenumber -1]<<endl;
      }
      cout <<"=============================="<<endl;

}


private:
    vector<string>_lines;
    map<string,set<int>>_wordnums;
    map<string,int>_dict;
};

int main()
{
      TextQuery tq;
    
    // 读取文件名
    string filename = "china_daily.txt";
    
    // 读取文件
    tq.read(filename);
    tq.query("Shenzhen");
    // 交互查询
    string queryWord;
    while (true) {
        cout << "\nEnter word to query (or 'q' to quit): ";
        if (!(cin >> queryWord)) break;
        
        if (queryWord == "q" || queryWord == "Q") break;
        
        tq.query(queryWord);
    }
    return 0;
}

